package yiran.depositcumulative;

import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import yiran.depositcumulative.api.DepositCumulativeAPI;

public class DepositPlaceholder extends PlaceholderExpansion {
    private final DepositCumulative plugin;
    private final DepositCumulativeAPI api;

    public DepositPlaceholder(DepositCumulative plugin, DepositCumulativeAPI api) {
        this.plugin = plugin;
        this.api = api;
    }

    @Override
    public @NotNull String getIdentifier() {
        return "depositcumulative";
    }

    @Override
    public @NotNull String getAuthor() {
        return "Yiran";
    }

    @Override
    public @NotNull String getVersion() {
        return plugin.getDescription().getVersion();
    }

    @Override
    public boolean persist() {
        return true;
    }

    @Override
    public String onRequest(OfflinePlayer offlinePlayer, String params) {
        // 处理全服累计总额
        if ("total_all".equalsIgnoreCase(params)) {
            return String.valueOf(api.getTotalDepositAll());
        }

        // 处理全服累计总额的格式化版本
        if ("total_all_formatted".equalsIgnoreCase(params)) {
            return formatNumber(api.getTotalDepositAll());
        }

        // 处理特定玩家的累计总额
        if (params.startsWith("total_")) {
            String playerName = params.substring(6);
            return String.valueOf(api.getTotalDeposit(playerName));
        }

        // 处理当前玩家的占位符
        switch (params.toLowerCase()) {
            case "total":
                if (offlinePlayer != null) {
                    return String.valueOf(api.getTotalDeposit(offlinePlayer));
                }
                return "0";

            case "total_formatted":
                if (offlinePlayer != null) {
                    return formatNumber(api.getTotalDeposit(offlinePlayer));
                }
                return "0";

            default:
                // 默认尝试查询玩家名称
                return String.valueOf(api.getTotalDeposit(params));
        }
    }

    private String formatNumber(int amount) {
        if (amount >= 1000000) {
            return String.format("%.1fM", amount / 1000000.0);
        } else if (amount >= 10000) {
            return String.format("%.1fW", amount / 10000.0);
        } else if (amount >= 1000) {
            return String.format("%.1fK", amount / 1000.0);
        }
        return String.valueOf(amount);
    }
}
